package com.GamersCom.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.GamersCom.db.User;
import com.GamersCom.model.MgrFactory;
import com.GamersCom.model.UserMgr;

/**
 * Servlet implementation class LookupUser
 */
public class LookupUser extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		process(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		HttpSession session = request.getSession();
		String nextView;
		String username = (String) session.getAttribute("username");

		// redirect to the login
		if (username == null)
		{
			nextView = "login.jsp";
		}
		else
		{

			// This search function is for admin user only for now. The full
			// version
			// will be completed in Milestone 3.
			String search = request.getParameter("searchcontent");
			String criteria = request.getParameter("criteria");

			// get the DAOFactory and userMgr
			MgrFactory factory = (MgrFactory) this.getServletContext()
					.getAttribute("mgrFactory");
			UserMgr userMgr = factory.getUserMgr();

			// retrieve the user by the search criteria
			User user = null;
			if (criteria.equals("username"))
			{
				user = userMgr.getUserByUsername(search);
			}
			else if (criteria.equals("email"))
			{
				user = userMgr.getUserByEmail(search);

			}

			List<User> userList = new ArrayList<User>();
			userList.add(user);

			if (user == null)
			{
				request.setAttribute("msg", "Can not find the user!");
				nextView = "/adminUsers.jsp";
			}
			else
			{
				request.setAttribute("userList", userList);
				nextView = "adminUsers.jsp";
			}
		}
		request.getRequestDispatcher(nextView).forward(request, response);
	}

}
